package cn.jimmie.learn.viewArt.weight

import android.content.Context
import android.util.AttributeSet
import android.view.ViewGroup
import kotlin.math.max

/**
 * function :
 *
 * <p> Create Time:  2019年01月21日 12:35 </p>
 * <p> @author Jimmie.Qian  </p>
 */
class EasyVertLayout(context: Context?, attrs: AttributeSet?) : ViewGroup(context, attrs) {

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        var localWidth = MeasureSpec.getSize(widthMeasureSpec)
        var localHeight = MeasureSpec.getSize(heightMeasureSpec)

        for (index in 0..childCount) {
            val child = getChildAt(index) ?: continue

            val lp = child.layoutParams as MarginLayoutParams

            child.measure(
                getChildMeasureSpec(widthMeasureSpec, lp.leftMargin + lp.rightMargin, lp.width),
                getChildMeasureSpec(heightMeasureSpec, lp.topMargin + lp.bottomMargin, lp.height)
            )
            val childWidth = lp.leftMargin + lp.rightMargin + child.measuredWidth
            val childHeight = lp.topMargin + lp.bottomMargin + child.measuredHeight
            localWidth = max(localWidth, childWidth)
            localHeight += childHeight
        }
        super.onMeasure(
            MeasureSpec.makeMeasureSpec(localWidth, MeasureSpec.EXACTLY),
            MeasureSpec.makeMeasureSpec(localHeight, MeasureSpec.EXACTLY)
        )
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        var layoutTop = t
        for (index in 0..childCount) {
            val child = getChildAt(index) ?: continue
            val lp = child.layoutParams as MarginLayoutParams

            child.layout(
                l + lp.leftMargin,
                layoutTop + lp.topMargin,
                l + lp.leftMargin + child.measuredWidth,
                layoutTop + lp.topMargin + child.measuredHeight
            )
            layoutTop += lp.topMargin + child.measuredHeight + lp.bottomMargin
        }
    }

    override fun generateLayoutParams(attrs: AttributeSet?): MarginLayoutParams {
        return MarginLayoutParams(context, attrs)
    }
}